<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 * @author   howe <howe1995@163.com>
 */

namespace App\Cache;

use App\Cache\Repository\HashRedis;

/**
 * 服务运行ID - 缓存助手.
 */
class ServerRunID extends HashRedis
{
    /**
     * 运行检测超时时间（单位秒）.
     */
    public const RUN_OVERTIME = 35;

    protected $prefix = 'SERVER_RUN_ID';

    protected $name = '';

    /**
     * 获取服务ID列表.
     *
     * @param int $type 获取类型[1:正在运行;2:已超时;3:所有]
     */
    public function getServerRunIdAll(int $type = 1): array
    {
        $arr = $this->all();

        if ($type == 3) {
            return $arr;
        }

        $current_time = time();
        return array_filter($arr, function ($value) use ($current_time, $type) {
            if ($type == 1) {
                return ($current_time - intval($value)) <= self::RUN_OVERTIME;
            }
            return ($current_time - intval($value)) > self::RUN_OVERTIME;
        });
    }
}
